const db = require("../models");

class CabinetsGrpRepositories {
  async addNewCabinetsGrp(cabinetsGrpData) {
    try {
      const newCabinetsGrp = await db.CabinetsGrp.create(cabinetsGrpData);
      return newCabinetsGrp;
    } catch (error) {
      throw error;
    }
  }

  async delCabinetsGrpById(id) {
    const cabinetsGrp = await db.CabinetsGrp.findOne({ where: { id } });
    return cabinetsGrp ? (await cabinetsGrp.destroy(), true) : false;
  }

  async delCabinetsGrpByName(name) {
    const cabinetsGrp = await db.CabinetsGrp.findOne({ where: { name } });
    return cabinetsGrp ? (await cabinetsGrp.destroy(), true) : false;
  }

  async updateCabinetsGrpById(id, cabinetsGrpData) {
    const [affectedRows] = await db.CabinetsGrp.update(cabinetsGrpData, {
      where: { id },
    });
    return affectedRows > 0; // 返回是否更新成功
  }

  async getCabinetsGrpById(id) {
    return await db.CabinetsGrp.findOne({ where: { id } });
  }

  async getCabinetsGrpByName(name) {
    return await db.CabinetsGrp.findOne({ where: { name } });
  }

  async getAllCabinetsGrps() {
    return await db.CabinetsGrp.findAll();
  }

  // 取柜子分组的 id 和 name 的映射数组
  async getMapofCabinetsGrps() {
    const cabinetsGrps = await db.CabinetsGrp.findAll({
      attributes: ['id', 'name'], // 只查询 id 和 name 字段
    });

    // 转换结果为 [{ id: name }, ...] 格式
    return cabinetsGrps.map(cabinetGrp => ({
      value: cabinetGrp.id,
      label: cabinetGrp.name
    }));
  }
}

module.exports = new CabinetsGrpRepositories();
